var express = require('express');
var router = express.Router();
var User = require('../models/User');
var ccap = require('ccap');
var session = require('express-session');
var testmid = require('../middleware');
//var testmid2= require('../middleware/index2');
var reqtool = require('../utils/reqtool');
var psw = require('../utils/passwordproducter');
var mailsender = require('../utils/mailsender');

var remoteServer = {
    host: 'innovation.yonyou.com',
    port: 80,
};
var captcha = ccap({
    width: 200,//set width,default is 256
    height: 60,//set height,default is 60
    offset: 50,//set text spacing,default is 40
    quality: 100,//set pic quality,default is 50
    fontsize: 57,//set font size,default is 57
    _text_len: 4,
    generate: function () {//Custom the function to generate captcha text
        var str_ary = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H',
            'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'];
        var str_num = 4,
            r_num = str_ary.length,
            text = '';
        for (var i = 0; i < str_num; i++) {
            var pos = Math.floor(Math.random() * r_num)
            text += str_ary[pos];//生成随机数
        }
        return text;

    }

});

/* GET home page. */
router.get('/', function (req, res, next) {
    //指到pc网页
    res.redirect('invite');

});
router.get('/invitecode', function (req, res, next) {
    var ary = captcha.get();
    req.session.invitecode = ary[0];
    res.end(ary[1]);
    console.log(ary[0]);
    // console.log(req.session);

});
router.get('/invite', function (req, res, next) {
    var deviceAgent = req.headers['user-agent'].toLowerCase();
    var agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);
    //console.log("agentID"+agentID);
    if (agentID) {
        //指到手机、pad的网页
        res.render('mobileinvite');
    } else {
        //指到pc网页
        res.render('invite');
    }
});
router.post('/invitemobile', function (req, res, next) {

    var account = req.param('email');
    //var h=req.headers['Accept']='application/json; charset=utf-8';
    var o = {};
    o.options = {
        host: remoteServer.host,
        port: remoteServer.port,
        path: '/user/alpha/isUniqueEmail/' + account,
        method: 'GET',
        //  headers: h
    };
    reqtool(o, function (resb, data) {
        data = JSON.parse(data);
        if (!data.result) {
            var emsg = '邮箱"' + account + '"已经注册过账号,可以直接登陆,如忘记密码,可通过找回密码功能找回';
            res.json({code: -1, error: {type: 'email', msg: emsg}});
            return
        }
        User.findOne({email: account}, function (err, user) {
            if (err) {
                console.log(err);
                return;
            }
            if (user && user.state == 0) {
                res.json({code: -1, error: {msg: '邮箱"' + account + '"已经提交过内测申请,工作人员将在1-3个工作日完成审核'}});
                return
            }

            if (user && user.state == 1) {
                res.json({code: -1, error: {msg: '邮箱"' + account + '"已经提交过内测申请,已经通过审核,请到mobileplus登录'}});
                return;
            }
            new User({
                'name': req.param('username'),
                'phone': req.param('phone'),
                'email': req.param('email'),
                'company': req.param('company'),
                'captcha': req.param('invitereason'),
                'state': 0,
                'date': new Date()
            }).save(function (err) {
                if (err) {
                    res.json({code: -1, error: {msg:"您的数据有点小问题"}});
                } else {
                    res.json({code: 1, success: {msg: "申请已提交！工作人员将在1-3个工作日完成审核，审核通过后会将内测账号和密码发至您的邮箱，请注意查收！"}});
                }
            });
        });
    });
});

router.post('/invite', function (req, res, next) {
    if (req.session.invitecode && req.session.invitecode.toLowerCase() != req.param('validateCode').toLowerCase()) {
        res.json({code: -1, error: {msg: "验证码过期或者错误"}});
        return;
    }
    var account = req.param('email');
    var o = {};
    o.options = {
        host: remoteServer.host,
        port: remoteServer.port,
        path: '/user/alpha/isUniqueEmail/' + account,
        method: 'GET',
        //  headers: h
    };
    reqtool(o, function (resb, data) {
        data = JSON.parse(data);
        if (!data.result) {
            var emsg = '邮箱"' + account + '"已经注册过账号,可以直接登陆,如忘记密码,可通过找回密码功能找回';
            res.json({code: -1, error: {type: 'email', msg: emsg}});
            return
        }
        User.findOne({email: account}, function (err, user) {
            if (err) {
                console.log(err);
                return;
            }
            if (user && user.state == 0) {
                res.json({code: -1, error: {msg: '邮箱"' + account + '"已经提交过内测申请,工作人员将在1-3个工作日完成审核'}});
                return
            }

            if (user && user.state == 1) {
                res.json({code: -1, error: {msg: '邮箱"' + account + '"已经提交过内测申请,已经通过审核,请到mobileplus登录'}});
                return;
            }
            new User({
                'name': req.param('username'),
                'phone': req.param('phone'),
                'email': req.param('email'),
                'company':req.param('company'),
                'captcha': req.param('invitereason'),
                'state': 0,
                'date': new Date()
            }).save(function (err) {
                if (err) {
                    console.log(err);
                    res.json({code: -1, error: {msg: "您的数据有点小问题"}});
                } else {
                    res.json({code: 1, success: {msg: "申请已提交！工作人员将在1-3个工作日完成审核，审核通过后会将内测账号和密码发至您的邮箱，请注意查收！"}});
                }
            });
        });
    });
});
router.get('/invite/users', function (req, res, next) {

    if (req.session.admin) {
        User.find(function (err, users) {
            if (err) console.log(err);
            if (users) {
                res.render('users', {d: users});
            }
        });
    } else {
        res.redirect('login');
    }
});

router.get('/invite/login', function (req, res, next) {
    if (!req.session.admin) {
        res.render('login', {title: '后台登陆'});
    } else {
        res.redirect('/invite/users');
    }
});
router.post('/invite/login', function (req, res, next) {
    var name = req.param('name');
    var passwd = req.param('password');
    if (name == 'admin' && passwd == 'yonyou') {
        req.session.admin = {
            name: name,
            passwd: passwd
        }
        res.json({code: 1, success: {msg: "登陆成功"}});

    } else {
        res.json({code: -1, error: {msg: "用户名或者密码错误"}});
    }
});
router.get('/invite/loginout', function (req, res, next) {
    req.session.destroy();
    res.redirect('/invite/login')
});
router.post('/invite/users/update', function (req, res, next) {

    var state = Number(req.param('state'));
    var id = req.param('id');
    User.findOne({'_id': id}, function (err, user) {
        if (err) {
            console.log(err);
            return;
        }
        if (state == 1) {
            var o = {};
            o.options = {
                host: remoteServer.host,
                port: remoteServer.port,
                path: '/user/alpha/isUniqueEmail/' + user.email,
                method: 'GET',
                //  headers: h
            };
            reqtool(o, function (request1, data) {
                data = JSON.parse(data);
                //console.log(data.result);
                //如果账号系统有账号了,
                if (!data.result) {
                   // var emsg = '邮箱"' + user.email + '"已经注册过账号,可以直接登陆,如忘记密码,可通过找回密码功能找回';
                    //发邮件2
                    var msg = '<p>您好,邮箱' + user.email + '已经注册过移动+账号,如忘记密码,可点击<a href="http://mobileplus.yonyou.com/updatePwd">http://mobileplus.yonyou.com/updatePwd</a>找回密码+</p>'
                        + '<p>登陆<a href="http://mobileplus.yonyou.com">http://mobileplus.yonyou.com</a>试用移动+</p>';
                    mailsender.send(data, msg, function (e, info) {
                        if (e) {
                            res.json({code: -1, error: {msg: '发送邮件失败'}});
                        } else {
                            User.update({'_id': id}, {$set: {state: state}}, function (err, user) {
                                res.redirect('/invite/users');
                            });
                        }
                    });
                    return
                }


                var o = {};
                o.options = {
                    host: remoteServer.host,
                    port: remoteServer.port,
                    path: '/user/alpha/CreateAccount',
                    method: 'POST',
                    headers: {
                        //'Content-Type': 'application/x-www-form-urlencoded'  使用这种方式需要用querystring转换一下json
                        'Content-Type': 'application/json'
                    }
                    //  headers: h
                };
                var passwd = psw.ramPassword();
                o.data = '{"email": "' + user.email + '", "password": "' + passwd + '"}';
                //console.log('data----');
                //console.log(o.data);

                reqtool(o, function (request2, data) {
                    data = JSON.parse(data);
                    //console.log(data);
                    if (data._id) {
                        //发邮件
                        var msg = '<p>恭喜您,移动+内测申请通过,账号为' + data.username + ',密码为' + passwd + ',您可登陆<a href="http://mobileplus.yonyou.com">http://mobileplus.yonyou.com</a>使用移动+</p>';
                        mailsender.send(data, msg, function (e, info) {
                            if (e) {
                                res.json({code: -1, error: {msg: '发送邮件失败'}});
                            } else {
                                User.update({'_id': id}, {$set: {state: state}}, function (err, user) {
                                    res.redirect('/invite/users');
                                });
                            }
                        });
                    } else {
                        res.json({code: -1, error: {msg: "账户已经存在"}});
                    }
                });
            });
        }


        if(state==-1){
            User.update({'_id': id}, {$set: {state: state}}, function (err, user) {
                res.redirect('/invite/users');
            });
        }
    });


});
router.use(testmid);
router.post('/invite/users', function (req, res, next) {
    User.find(req.qparams, function (err, users) {
        err && console.log(err);
        if (users) {
            console.log(users);
            res.json({code: 1, success: {msg: '', data: users}});
        }
    });
});

module.exports = router;
